<template>
  <div id="three"></div>
  <div id="btu" @click="a2">
  </div>

</template>

<script lang="ts" setup name="Sence">
/* eslint-disable */
import { ref, onMounted, type Ref, onUnmounted } from 'vue';
import Viewer, { type Animate } from '@/modules/Viewer';

import ModelLoader from '@/modules/ModelLoder';
import * as THREE from 'three';

import Event from '@/modules/Viewer/Events';
import BoxHelperWrap from '@/modules/BoxHelperWrap';
import Floors from '@/modules/Floors';

let viewer: Viewer;
let modelLoader: ModelLoader;
let boxHelperWrap: BoxHelperWrap;
let floors: Floors;

interface Props {
  modelUrl: string
}

const props = defineProps<Props>()

const a2 = () => {
  viewer.destroy();
  setTimeout(() => {
    init();
    initModel()
  }, 2000);
}

onMounted(() => {
  init();
  initModel();

});
onUnmounted(() => {
  viewer.destroy();
});
const init = () => {
  viewer = new Viewer('three');
  // viewer.addAxis();
  viewer.initRaycaster();

  modelLoader = new ModelLoader(viewer);

  boxHelperWrap = new BoxHelperWrap(viewer);
  floors = new Floors(viewer);
  floors.addGird()
  viewer.emitter.on(Event.dblclick.raycaster, (list: THREE.Intersection[]) => {
    onMouseClick(list);
  });

  viewer.emitter.on(Event.mousemove.raycaster, (list: THREE.Intersection[]) => {
    onMouseMove(list);
  });

};

const initModel = () => {

  modelLoader.loadModelToScene(props.modelUrl, baseModel => {
    // modelLoader.loadModelToScene('http://127.0.0.1:8080/74LVC138Aa.glb', baseModel => {

    console.log(baseModel, '1111111');

    baseModel.setScalc(0.3);
    // baseModel.object.rotation.y = Math.PI / 2;
    const model = baseModel.gltf.scene;
    model.position.set(0, 0, 0);
    // model.name = '';
    baseModel.openCastShadow();


    const rackList: any[] = [];
    // model.traverse(item => {
    //   if (checkIsRack(item)) {
    //     rackList.push(item);
    //   }
    // });


    viewer.setRaycasterObjects(rackList);

  });
};



const onMouseClick = (intersects: THREE.Intersection[]) => {
};


const onMouseMove = (intersects: THREE.Intersection[]) => {
  if (!intersects.length) {

    boxHelperWrap.setVisible(false);
    return;
  }
  const selectedObject = intersects[0].object || {};


  let selectedObjectName = '';
  const findClickModel = (object: any) => {
    if (object.name.includes('CR4000')) {
      selectedObjectName = object.name;
      return;
    }
    if (object.parent) {
      findClickModel(object.parent);
    }
  };


  findClickModel(selectedObject);



};




</script>

<style scoped>
#three {
  height: 100%;
  width: 100%;
}

#btu {
  position: absolute;
}
</style>
